package com.zfp.core.interceptor;

import com.zfp.sys.entity.SysMenu;
import com.zfp.sys.entity.SysUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by Administrator on 2017/7/14.
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        HttpSession session = httpServletRequest.getSession();
        String url = httpServletRequest.getRequestURI();
//		System.out.println(">>>>>>>>>>>>>>>>>>>>");
//		System.out.println(url);
        // 判断url是否要登陆后才能进入
        // 这里公开地址是登陆提交的地址
        String NO_INTERCEPTOR_PATH = ".*/((sys/sysUser/toLogin.do)|(sys/sysUser/login.do)).*";
        if (url.matches(NO_INTERCEPTOR_PATH)) {
            return true;
        } else {
            // 判断session

            // 从session中取出用户身份信息
            SysUser sysUser = (SysUser) session.getAttribute("sessionUser");
            if (sysUser != null) {
                // 身份存在，放行
                return true;
            }
            // 执行这里表示用户身份需要认证，跳转登陆页面
            httpServletRequest.getRequestDispatcher("/index.jsp").forward(httpServletRequest,httpServletResponse);
            // return false表示拦截，不向下执行
            // return true表示放行
            return false;
        }


    }


    /**
     * 进入Handler方法之后，返回modelAndView之前执行,系统用来传输系统基本信息用
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

        SysUser sysUser = (SysUser)httpServletRequest.getSession().getAttribute("sessionUser");
        //modelAndView不为空时，传输系统基本信息。
        if(modelAndView != null){
            //no-skin skin-1 skin-2 skin-3

            modelAndView.addObject("sessionUser", sysUser);
//            List<SysMenu> topMenuList = (List<SysMenu>) httpServletRequest.getSession().getAttribute("sessionTopMenuList");
//            modelAndView.addObject("sessionTopMenuList", topMenuList);
        }


    }


    /**
     * 进入 Handler方法之前执行,用于身份认证、身份授权等操作 如果认证通过表示当前用户没有登陆，需要此方法拦截重定向到登陆页面 return
     * false表示拦截，不向下执行 return true表示放行
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
